﻿using System;
using System.Collections.Generic;
using System.Linq;
using Hopscotch.Common.Contracts.AppService;
using Hopscotch.Common.Extensions;
using Hopscotch.Domain.Finance;
using Hopscotch.Server.Common.Contracts;

namespace Hopscotch.Server.EnqServiceFake
{
    public class InstrumentEnqService : FakeEnqServiceIntKey<Instrument>, IInternalInstrumentEnqService
    {
        private static bool isInitialized;

        private readonly IInstrumentService instrumentService;

        public InstrumentEnqService(IInstrumentService instrumentService)
        {
            this.instrumentService = instrumentService;

            Initialize();
        }

        private void Initialize()
        {
            if (isInitialized)
                return;

            // Quickly nip through the Instrument App service and cache the same in the enquiry Instrument service
            const int InstrumentIdStart = 1000;
            const int TotalTestInstruments = 8;
            for (int i = 0; i < TotalTestInstruments; i++)
            {
                var instrumentId = InstrumentIdStart + i;
                var instrument = instrumentService.Get(instrumentId);

                Add(instrument);
            }

            isInitialized = true;
        }

        public ICollection<Instrument> Search(string search)
        {
            FakeDelay(500);

            var qry = from s in FakeData.Values
                      where (s.Symbol != null && s.Symbol.StartsWith(search, StringComparison.OrdinalIgnoreCase))
                      || (s.Name != null && s.Name.Contains(search, StringComparison.OrdinalIgnoreCase))
                      select s;

            return qry.ToList();
        }

    }
}
